package com.sc.web.gwt.client.view.uicomponent;


import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;

/**
 * A general purpose dialog class that can have a body widget and a set of buttons added to it.
 */
public class Dialog {

    // Using GWT.create() to simplify extension and hide implementation details.
    protected static final Resources RESOURCES = GWT.create(Resources.class);

    private final DialogBox dialogBox = new DialogBox(false, true);
    private final Panel bodyPanel = new FlowPanel();
    private final Panel buttonPanel = new FlowPanel();

    private final ClickHandler hideHandler = new ClickHandler() {
        public void onClick(ClickEvent event) {
            hide();
        }
    };

    public Dialog() {
        dialogBox.setAnimationEnabled(true);
        dialogBox.setGlassEnabled(true);

        RESOURCES.dialogCSS().ensureInjected();

        bodyPanel.addStyleName(RESOURCES.dialogCSS().bodyPanel());

        HorizontalPanel buttonAlignmentPanel = new HorizontalPanel();
        buttonAlignmentPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
        buttonAlignmentPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        buttonAlignmentPanel.add(buttonPanel);
        buttonAlignmentPanel.addStyleName(RESOURCES.dialogCSS().buttonPanel());

        FlowPanel outerPanel = new FlowPanel();
        outerPanel.addStyleName(RESOURCES.dialogCSS().outerPanel());

        outerPanel.add(bodyPanel);
        outerPanel.add(buttonAlignmentPanel);

        dialogBox.setWidget(outerPanel);
    }

    protected void setBody(Widget... widgets) {
        bodyPanel.clear();
        for (Widget widget : widgets) {
            bodyPanel.add(widget);
        }
    }

    /**
     * Adds a new button that will dismiss the dialog.
     *
     * @param button the button
     */
    protected void addButton(Button button) {
        // Clicking any button dismisses the dialog.
//        button.addClickHandler(hideHandler);

        if (hasButtons()) {
            button.addStyleName(RESOURCES.dialogCSS().buttonRightNeighbor());
        }

        buttonPanel.add(button);
    }

    private boolean hasButtons() {
        return buttonPanel.iterator().hasNext();
    }

    protected void setTitle(String title) {
        dialogBox.setText(title);
    }

    protected void center() {
        dialogBox.center();
    }

    protected void show() {
        dialogBox.show();
    }

    public void hide() {
        dialogBox.hide();
    }
}